<template>
  <div class="shelves-commodity">
    <div class="head-title">
      <i class="title">当前直播间</i>：<i class="name">{{ roomInfo.name }}</i>
      <i class="status">{{ roomInfo.liveStatusStr }}</i>直播时间段：
      <i class="time">{{ roomInfo.liveTime }}</i>
      <div class="back">
        <a-button @click="backPage">返回</a-button>
      </div>
    </div>
    <search-table
      :url="listUrl"
      ref="searchtable"
      :columns="columns"
      :defaultParams="defaultParams"
      :headParams="headParams"
      :xLength="1200"
      :form="form"
      :beforeRenderFunc="beforeRenderFunc">
      <!-- 搜索条件 -->
      <template slot="searchForm">
        <a-form layout="inline" :form="form">
          <a-form-item label="商品名称">
            <a-input style="width: 195px" allowClear v-decorator="['goodsName']" placeholder="请输入商品名称"></a-input>
          </a-form-item>
          <a-form-item label="商品ID">
            <a-input-number style="width: 195px" :precision="0" allowClear v-decorator="['goodsId']" placeholder="请输入商品ID"></a-input-number>
          </a-form-item>
          <a-form-item label="商品分组">
            <a-tree-select
                allowClear
                style="width: 195px"
                :replaceFields="{children:'children', title:'groupName', key:'id', value: 'id' }"
                v-decorator="[
                  'goodsGroupId',
                ]"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="productGroupList"
                placeholder="请选择"
                tree-default-expand-all
                >
                <span slot="title" slot-scope="{ value }">
                    {{ value }}
                </span>
            </a-tree-select>
          </a-form-item>
          <a-form-item label="商品状态">
            <a-select
              showSearch
              allowClear
              style="width: 195px"
              :options="liveGoodsStatusList"
              v-decorator="['putawayStatus']"
              placeholder="请选择">
            </a-select>
          </a-form-item>
        </a-form>
      </template>
      <!-- 操作栏 -->
      <template slot="oprationRow">
        <permission v-if="blong == 1 && (roomInfo.liveStatus == '101' || roomInfo.liveStatus == '102')" authority="product:goodsShelves">
          <a-button type="primary" @click="creatLive()">追加商品</a-button>
        </permission>
        <permission v-if="blong == 1" authority="shelvesCommodity:manager:sync">
          <a-button @click="syncLive($refs.searchtable.selectedRows)">同步商品数据</a-button>
        </permission>
      </template>
      <!-- 表格行操作 -->
      <template slot="tableOperation" slot-scope="{ record }">
        <a-space>
          <permission v-if="blong == 1 && ((roomInfo.liveStatus == '101' || roomInfo.liveStatus == '102' || roomInfo.liveStatus == '105') && (!record.putawayStatus || record.putawayStatus == '0'))" authority="product:goodsOnsale">
            <span class="text-primary pointer" @click="checkLiveRoom(record, '0')">上架</span>
          </permission>
          <permission v-if="blong == 1 && ((roomInfo.liveStatus == '101' || roomInfo.liveStatus == '102' || roomInfo.liveStatus == '105') && (record.putawayStatus == '1'))" authority="shelvesCommodity:manager:soldOut">
            <span class="text-primary pointer" @click="checkLiveRoom(record, '1')">下架</span>
          </permission>
          <permission v-if="blong == 1 && (roomInfo.liveStatus == '101' && record.putawayStatus == '1')" authority="product:pushGoods">
            <span class="text-primary pointer" @click="pushCommodity(record)">推送</span>
          </permission>
          <permission authority="product:deleteGoods">
            <span class="text-danger pointer" @click="deleteLive(record)">移除</span>
          </permission>
        </a-space>
      </template>
    </search-table>
    <!-- 追加商品 -->
    <commodity-form ref="commodityForm" :roomId="roomId" :appId="appId" :hasChosenGoodsIds="hasChosenGoodsIds" @cancel="closeModal"></commodity-form>
  </div>
</template>

<script>
  import commodityForm from './components/commodityForm.vue';
  import { findDictNameByValue,createOptionsByDict } from '@/utils/dict'
  export default {
    name: "MarketingShelvesCommodity",
    components: {
      commodityForm
    },
    computed: {
      // 直播间id
      roomId() {
        return this.$route.query.id || "";
      },
      // 所属店铺
      blong() {
        return this.$route.query.blong || "";
      },
      // 直播平台
      appId() {
        return this.$route.query.appId || "";
      },
      // 用户信息
      userInfo(){
        return this.$store.getters.userInfo || {};
      }
    },
    data() {
      return {
        listUrl: '/product/selectByRoom', // 列表接口地址
        form: this.$form.createForm(this, { name: "table_search" }), // 搜索条件表单
        headParams: { baseURL: '/goldenhome/gh/live/admin' }, // 列表接口域名
        defaultParams: { // 列表默认携带参数
          appId: this.$route.query.appId,
          roomId: this.$route.query.id
        },
        handle: '', // 操作类型
        liveGoodsStatusList: createOptionsByDict('LIVE_GOODS_STATUS'), // 直播间状态
        productGroupList:[], // 商品分组
        hasChosenGoodsIds: [], // 已被选择的商品id集合
        columns: [
          {
            title: "商品ID",
            dataIndex: "goodsId",
            width: 125,
            key: "goodsId",
          },
          {
            title: "商品名称",
            dataIndex: "name",
            width: 125,
            key: "name"
          },
          {
            title: "商品图片",
            dataIndex: "coverImgLocal",
            width: 125,
            key: "coverImgLocal",
            customRender: (text, record) => {
              if(text) {
                return <table-img src={text}/>
              } else {
                return <table-img src={record.coverImgUrl}/>
              }
            }
          },
          {
            title: "商品分组",
            dataIndex: "goodsGroupName",
            width: 125,
            key: "goodsGroupName"
          },
          {
            title: "价格类型",
            dataIndex: "priceType",
            width: 125,
            key: "priceType",
            customRender: (text, record) => findDictNameByValue('LIVE_GOODS_PRICE', text)
          },
          {
            title: "价格",
            dataIndex: "price",
            width: 100,
            key: "price",
            customRender: (text, record) => {
              let res = ''
              if(record.priceType == 1){
                res = (Number(record.price)/100).toFixed(2)+'元'
              } else if(record.priceType == 2) {
                res = (Number(record.price)/100).toFixed(2)+'元 - '+(Number(record.price2)/100).toFixed(2)+'元'
              } else if(record.priceType == 3) {
                res = <span>市场价 {(Number(record.price)/100).toFixed(2)}元<br/>现价 {(Number(record.price2)/100).toFixed(2)}元</span>
              }
              return res
            }
          },
          {
            title: "添加方式",
            dataIndex: "thirdPartyTag",
            width: 125,
            key: "thirdPartyTag",
            customRender: (text, record) => findDictNameByValue('LIVE_GOOD_SOURCE', text)
          },
          {
            title: "库存",
            dataIndex: "goodsInventoryTotal",
            width: 100,
            key: "goodsInventoryTotal",
            customRender: (text, record) => {
              return text ? (text + (record.goodsUnitCode ? findDictNameByValue('GOOD_INVENTORY_UNIT', record.goodsUnitCode) : '')) : ''
            }
          },
          // {
          //   title: "订单量",
          //   dataIndex: "orderSales",
          //   width: 100,
          //   key: "orderSales"
          // },
          // {
          //   title: "销量",
          //   dataIndex: "realSales",
          //   width: 100,
          //   key: "realSales"
          // },
          // {
          //   title: "浏览量",
          //   dataIndex: "viewTotal",
          //   width: 100,
          //   key: "viewTotal"
          // },
          {
            title: "商品状态",
            dataIndex: "putawayStatus",
            width: 125,
            key: "putawayStatus",
            customRender: (text, record) => findDictNameByValue('LIVE_GOODS_STATUS', text)
          },
          {
            title: "操作",
            dataIndex: "operation",
            fixed: 'right',
            width: 125,
            scopedSlots: { customRender: "operation" },
          }
        ],
        roomInfo: {}
      }
    },
    watch: {},
    created() {
      this.getLiveInfo();
      this.getProductGroup();
    },
    mounted() {},
    methods: {
      // 获取直播间所有追加商品id集合
      getAllChosenGoodsIds() {
        this.$get('/product/selectByRoomForIds',
          {
            appId: this.appId,
            roomId: this.roomId
          },
          { baseURL: `${location.origin}/goldenhome/gh/live/admin` })
        .then(res => {
          if(res && res.returnCode=='1000'){
            this.hasChosenGoodsIds = res.dataInfo
          }
        })
      },
      // 处理表格数据
      beforeRenderFunc(data) {
        this.getAllChosenGoodsIds()
        return data
      },
      // 返回上一页
      backPage() {
        this.$router.push({
        name: "MarketingLiveRoom",
        query: {
          current:this.$route.query.current||1,
          blong: this.$route.query.blong,
          appId:this.$route.query.appId||this.formData.appId
        }
      });
      },
      // 关闭弹窗
      closeModal (freshTable) {
        console.log(freshTable)
        if (freshTable) {
          this.$refs.searchtable.refreshTable()
        }
      },
      // 获取直播间信息
      async getLiveInfo() {
        let res = await this.$get('/room/id',
          {
            appId: this.appId,
            roomId: this.roomId
          },
          { baseURL: `${location.origin}/goldenhome/gh/live/admin` });
        if(res && res.returnCode=='1000'){
          if(res.dataInfo){
            res.dataInfo.liveStatusStr = findDictNameByValue('LIVE_STATUS', res.dataInfo.liveStatus)
            res.dataInfo.liveTime = (res.dataInfo.startTime || '')+'至'+(res.dataInfo.endTime || '')
            this.roomInfo = res.dataInfo
          }
        }
      },
      //商品分组
      async getProductGroup(){
        let res=await this.$get('/goods/group/tree',{
          shopId:this.userInfo.shopId || ''
        },false,true);
        if(res && res.returnCode=='1000'){
          this.productGroupList=res.dataInfo || [];
        }
        else {
          this.productGroupList=[];
        }
      },
      // 追加商品
      creatLive() {
        this.$refs.commodityForm.formVisible = true;
      },
      // putawayStatus  1上架 0下架
      checkLiveRoom(record, type) {
        let _this = this, txt = ''
        let params = {}
        params.goodsId = record.goodsId
        params.id = record.id
        params.roomId = this.roomId
        params.appId = this.appId
        if (type == '1') {
          params.putawayStatus = 0
          txt = '下架成功'
        } else if (type == '0') {
          params.putawayStatus = 1
          txt = '上架成功'
        }
        this.$post('/product/goodsOnsale',
            params,
            { baseURL: `${location.origin}/goldenhome/gh/live/admin` }).then((res) => {
          if (res && res.returnCode == 1000) {
            _this.$message.success(txt);
            _this.$refs.searchtable.refreshTable();
          }
        });
      },
      // 推送
      pushCommodity(record) {
        let params = {}
        params.goodsId = record.goodsId
        params.id = record.id
        params.roomId = this.roomId
        params.appId = this.appId
         this.$post('/product/pushGoods',
            params,
            { baseURL: `${location.origin}/goldenhome/gh/live/admin` }).then((res) => {
          if (res && res.returnCode == 1000) {
            _this.$message.success('推送成功');
            _this.$refs.searchtable.refreshTable();
          }
        });
      },
      // 删除商品
      deleteLive(record) {
        let _this = this;
        this.$confirm({
          title: '删除操作',
          content: '是否确定移除该商品？',
          okText: '确认删除',
          cancelText: '取消',
          onOk() {
            _this.$post('/product/deleteGoods',
                {
                  appId: _this.appId,
                  roomId: _this.roomId,
                  id: record.id,
                  goodsId: record.goodsId
                },
                { baseURL: `${location.origin}/goldenhome/gh/live/admin` }).then((res) => {
              if (res && res.returnCode == 1000) {
                _this.$refs.searchtable.refreshTable();
              }
            });
          },
          onCancel() {},
        });
      },
      // 同步商品数据
      syncLive(records) {
        let _this = this;
        let goodsIds = records.map((item) => {
          return item.goodsId
        })
        let params = {}
        params.goodsIds = goodsIds
        params.roomId = this.roomId
        params.appId = this.appId
        this.$post('/product/syncselect',
            params,
            { baseURL: `${location.origin}/goldenhome/gh/live/admin` }).then((res) => {
          if (res && res.returnCode == 1000) {
            _this.$message.success('同步成功');
            _this.$refs.searchtable.refreshTable();
          }
        });
      },
    }
  }
</script>

<style scoped lang="less">
.shelves-commodity{
  .head-title{
    position: relative;
    background: #f5f5f5;
    padding: 20px 200px 0 32px;
    font-size: 14px;
    i{
      font-style: normal;
      font-size: 16px;
    }
    .title{
      color: #333333;
      font-weight: bold;
    }
    .status{
      font-size: 16px;
      color: #FD0000;
      font-weight: bold;
      margin: 0 15px;
    }
    .back{
      position: absolute;
      top: 10px;
      right: 20px;
    }
  }
}
</style>
